package com.lost.octopus.es.helper.entity.wrapper;

import com.lost.octopus.es.helper.entity.model.FieldConfig;
import com.lost.octopus.es.helper.builder.FieldMatchBuilders;
import com.lost.octopus.es.helper.constant.EsSearchMode;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;

import javax.annotation.Resource;

import static com.lost.octopus.es.helper.constant.EsSearchMode.WRAPPER_DEFAULT;

/**
 * 抽象的接口实现
 * @author zhangbh
 **/
public abstract class AbstractQueryWrapper implements QueryWrapper {

    @Resource
    protected FieldMatchBuilders fieldMatchBuilders;

    protected QueryBuilder useBuilder(FieldConfig config) {
        return fieldMatchBuilders.useBuilder(config);
    }

    /**
     * 获取模式
     * @return 查询模式
     */
    protected EsSearchMode defaultMode() {
        return EsSearchMode.SEARCH_MUST;
    }

    /**
     * 获取模式，否则默认
     * @param field 查询对象
     * @return 返回
     */
    protected EsSearchMode getMode(FieldConfig field) {
        return field.getSearchMode() == WRAPPER_DEFAULT ? defaultMode() : field.getSearchMode();
    }


    protected void useMode(BoolQueryBuilder builder, QueryBuilder otherBuilder, EsSearchMode mode) {
        switch (mode) {
            case SEARCH_MUST:
                builder.must(otherBuilder);
                break;
            case SEARCH_MUST_NOT:
                builder.mustNot(otherBuilder);
                break;
            case SEARCH_SHOULD:
            default:
                builder.should(otherBuilder);
                break;
        }
    }
}
